package utils

import (
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	"gitee.com/ameise84/e3utils/math"
)

func IfThenElse[T any](ok bool, t, f T) T {
	if ok {
		return t
	}
	return f
}

func CalcPct[T math.Number](a, b T) float64 {
	if b == 0 {
		return 0
	}
	return float64(a) * 100 / float64(b)
}

func GetMonthTableName(base string, t time.Time) string {
	t1 := t.UTC()
	key := fmt.Sprintf("%04d%02d", t1.Year(), t1.Month())
	return base + key
}

func ColRowToIndex(c, r int, maxCol int) int {
	return c + r*maxCol
}

func IndexToColRow(idx int, maxCol int) (c, r int) {
	c = idx % maxCol
	r = idx / maxCol
	return
}

func GetCurrentExtFileName() string {
	exePath, err := os.Executable()
	if err != nil {
		panic(err)
	}
	base := filepath.Base(exePath)
	ext := path.Ext(base)
	return strings.TrimSpace(strings.TrimSuffix(base, ext))
}

func GetCurrentExeDir() string {
	exePath, err := os.Executable()
	if err != nil {
		panic(err)
	}
	return filepath.Dir(exePath)
}

func GetCurrentWorkDir() string {
	dir, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	return dir
}
